package cn.iocoder.yudao.adminserver.franky.LRU;

import java.util.*;

/**
 * @Description:
 * @Author: franky
 * @CreateDate: 2021/4/14 12:01 下午
 * @Version: 1.0
 */
public class LRUCache {

    int capacity;
    Map<Integer, Object> lruMap;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        lruMap = new LinkedHashMap<>();
    }

    public Object get(int key) {
        if (null == lruMap.get(key)) {
            return -1;
        }
        // 刷新
        Object value = lruMap.remove(key);
        lruMap.put(key, value);
        return value;
    }

    public void put(int key, Object value) {
        lruMap.remove(key);
        lruMap.put(key, value);
        if (lruMap.size() > capacity) {
            lruMap.remove(lruMap.entrySet().iterator().next().getKey());
        }
    }

    public static void main(String[] args) {
        LRUCache lruCache = new LRUCache(10);
        for (int i = 1; i < 11; i++) {
            lruCache.put(i, i);
        }
        System.out.println(lruCache.lruMap);
        lruCache.put(1, 1);
        System.out.println(lruCache.lruMap);
        lruCache.get(5);
        System.out.println(lruCache.lruMap);
    }

}
